<template>
  <section class="component modify-config">
    <el-tabs v-model="currentTab">
      <el-tab-pane label="规则基本信息" name="config-base">
        <config-base v-model="configBaseModel" :isDisabled="isDisabled" ref="config-base"></config-base>
      </el-tab-pane>
      <el-tab-pane label="分配规则" name="distribute-rule">
        <distribute-rule v-model="distributeModel" :isDisabled="isDisabled" ref="distribute-rule" @strategyCaseTypeChange="strategyCaseTypeChange"></distribute-rule>
      </el-tab-pane>
      <el-tab-pane label="设置分案策略" name="distribution-pattern" v-if="this.distributeModel.strategyCaseType === 'OUTSOURCE_TO_COLLECTOR'|| this.distributeModel.strategyCaseType === 'VISIT_TO_COLLECTOR'|| this.distributeModel.strategyCaseType === 'TEL_TO_COLLECTOR'">
        <distribution-pattern v-model="distributeMode" :isDisabled="isDisabled" ref="distribution-pattern"></distribution-pattern>
      </el-tab-pane>
    </el-tabs>
    <div class="operate-buttons">
      <el-button @click="emitClose">取消</el-button>
      <el-button @click="submit" :disabled="isDisabled">确定</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Watch } from "vue-property-decorator";
import ConfigBase from "./config-base.vue";
import DistributeRule from "./distribute-rule.vue";
import DistributionPattern from "~/components/distribution-common/distribution-pattern.vue";
import { CaseApplyRecordService } from "~/services/domain-service/case-apply-record.service";
import { ApplyType} from "~/config/enum.config";
import { StrategyConfigService } from "~/services/management-service/strategy-config.service";
import { FlowTaskService } from '~/services/domain-service/flow-task.service';

@Component({
  components: {
    ConfigBase,
    DistributeRule,
    DistributionPattern
  }
})
export default class ModifyConfig extends Vue {
  @Dependencies(CaseApplyRecordService)
  private caseApplyRecordService: CaseApplyRecordService;
  @Dependencies(StrategyConfigService) private strategyConfigService: StrategyConfigService;
  @Dependencies(FlowTaskService)
  private flowTaskService: FlowTaskService;

  @Prop()
  private strategyId: any;
  @Prop()
  private applyId: any;
  @Prop()
  private isDisabled:any

  private currentTab = "config-base"

  private id = ""
  private distributeMode = ""
  private distributeModel: any = {};
  private configBaseModel: any = {};
  private createApplyType = ApplyType.createStrategy.value;
  private updateApplyType = ApplyType.updateStrategy.value;

  @Emit('close')
  private emitClose() { this.currentTab = 'config-base'}

  @Emit('success')
  private emitSuccess() {
    this.$message.success('操作成功')
    this.emitClose()
  }

  // @Watch('strategyId', { immediate: true })
  // private onStrategyIdChange(val) {
  //   console.log(val,11)
  //   if (val) {
  //     this.strategyConfigService.getOneById(val).subscribe(this.revertDataNext)
  //   } else {
  //     this.initData()
  //   }
  // }
  private refresh(){
    //TODO 当使用组件传的是applyId时调用caseApplyRecordService.getOneById接口
    if(this.applyId){
      this.caseApplyRecordService.getOneById(this.applyId).subscribe(this.revertDataNext)
    }
    if (this.strategyId) {
      this.strategyConfigService.getOneById(this.strategyId).subscribe(this.revertDataNext)
    } else {
      this.initData()
    }
  }
  private strategyCaseTypeChange(val){
    console.log(val,"val")
    this.distributeModel.strategyCaseType = val
  }
  private submit() {
    const panels = ['config-base', 'distribute-rule']
    const validates = panels.map(v => {
      const component = this.$refs[v] as any
      return component.validate().catch(e => Promise.reject(e))
    })
    Promise.all(validates).then(x => {
      if (!this.distributeMode&&(this.distributeModel.strategyCaseType === 'OUTSOURCE_TO_COLLECTOR'|| this.distributeModel.strategyCaseType === 'VISIT_TO_COLLECTOR'|| this.distributeModel.strategyCaseType === 'TEL_TO_COLLECTOR')) {
        this.$message('请设置分案策略')
        this.currentTab = 'distribution-pattern'
        return
      }
      const result = { ...this.distributeModel, ...this.configBaseModel, distributeMode: this.distributeMode, strategyId: this.id }
      
      if (this.id) {
        console.log(result)
        result.applyCategory = this.updateApplyType
        // this.caseApplyRecordService.approvalStrategyConfig(result).subscribe(this.emitSuccess)
      } else {
        result.applyCategory = this.createApplyType
        // this.caseApplyRecordService.approvalStrategyConfig(result).subscribe(this.emitSuccess)
      }
      this.flowTaskService
      .checkApplyCategory({ applyCategory: result.applyCategory })
      .subscribe((data) => {
        // 0 拒绝，1 提示，2 通过
        console.log(data,"提示")
        if (data.status === 1) {
          this.$confirm("该" + this.$dict.getDictName(result.applyCategory, 'ApplyCategory') + "申请将直接生效，是否继续?", '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.caseApplyRecordService.approvalStrategyConfig(result).subscribe(this.emitSuccess)
          }).catch(() => {
           
          });
        } else if (data.status === 2) {
          this.caseApplyRecordService.approvalStrategyConfig(result).subscribe(this.emitSuccess)
        }else{
          this.$message.error(data.message);
        }
      });
    }).catch(v =>{
      console.log(v,"v")
      this.currentTab = v
    } )
  }

  private initData() {
    this.currentTab = 'config-base'
    this.id = ""
    this.distributeModel = {
      assignModel: "",
      departmentId: "",
      strategyCaseType: "",
      users: [],
      userName:[],
      outsourceIds:[],
      outsourceName:[]
    }
    this.configBaseModel = {
      commonState: "",
      formulaJson: "[]",
      name: "",
      strategyType: "",
      priority: 5
    }
    this.distributeMode = ""
    const configBaseTab: any = this.$refs['config-base']
    if (configBaseTab) configBaseTab.reset()
    const distributeRuleTab: any = this.$refs['distribute-rule']
    if (distributeRuleTab) distributeRuleTab.reset()
  }

  /**
   * 回显数据下一步
   */
  private revertDataNext(val) {
    this.id = val.id
    this.distributeModel = {
      assignModel: val.assignModel,
      departmentId: val.departmentId,
      strategyCaseType: val.strategyCaseType,
      users: val.userList,
      userName:val.userNames,
      outsourceIds:val.outsourceList,
      outsourceName:val.outsourceNames
    }
    this.configBaseModel = {
      commonState: val.commonState,
      formulaJson: val.formulaJson,
      name: val.name,
      strategyType: val.strategyType,
      priority: val.priority
    }
    this.distributeMode = val.distributeMode
  }

  private created() {
    this.initData()
  }
}
</script>

<style lang="less" scoped>
</style>
